package org.dromara.run.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.dromara.basic.domain.vo.PlaceVo;
import org.dromara.basic.domain.vo.TeachClassVo;
import org.dromara.basic.service.IPlaceService;
import org.dromara.basic.service.ITeachClassService;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.service.ScheduleService;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.run.domain.vo.RuleVo;
import org.dromara.run.service.IDeptService;
import org.dromara.run.service.IRuleService;
import org.springframework.stereotype.Service;
import org.dromara.run.domain.bo.ScheduleBo;
import org.dromara.run.domain.vo.ScheduleVo;
import org.dromara.run.domain.Schedule;
import org.dromara.run.mapper.ScheduleMapper;
import org.dromara.run.service.IScheduleService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 阳光跑计划表Service业务层处理
 *
 * @author chl
 * @date 2024-08-30
 */
@RequiredArgsConstructor
@Service
public class ScheduleServiceImpl implements IScheduleService, ScheduleService {

    private final ScheduleMapper baseMapper;
    private final IRuleService ruleService;
    private final IDeptService deptService;
    private final IPlaceService iPlaceService;
    private final ITeachClassService teachClassService;

    /**
     * 查询阳光跑计划表
     */
    @Override
    public ScheduleVo queryById(Long scheduleId){
        return baseMapper.selectVoById(scheduleId);
    }

    /**
     * 查询阳光跑计划表列表
     */
    @Override
    public TableDataInfo<ScheduleVo> queryPageList(ScheduleBo bo, PageQuery pageQuery) {
        QueryWrapper<Schedule> lqw = buildQueryWrapper(bo);
        Page<ScheduleVo> result = baseMapper.selectScheduleList(pageQuery.build(), lqw,bo);
        List<ScheduleVo> records = result.getRecords();
        for (ScheduleVo scheduleVo:records) {
            String ruleId = scheduleVo.getRuleId();
            String college = scheduleVo.getCollegeId();
            String yearGroups = scheduleVo.getClassId();
            String locations=scheduleVo.getLocation();
//            String professional=scheduleVo.getProfessional();
            if(StringUtils.isNotEmpty(ruleId)){
                List<Long> ruleIds = Arrays.stream(ruleId.split(",")).map(Long::parseLong).collect(Collectors.toList());
                List<String> ruleList=new ArrayList<>();
                for(Long id:ruleIds){
                    RuleVo ruleVo = ruleService.queryById(id);
                    ruleList.add(ObjectUtil.isNull(ruleVo) ? null : ruleVo.getRuleName());
                }
                scheduleVo.setRuleNames(ruleList);
            }
            if(StringUtils.isNotEmpty(locations)){
                List<Long> locationIds= Arrays.stream(locations.split(",")).map(Long::parseLong).collect(Collectors.toList());
                List<String> locationNames=new ArrayList<>();
                for(Long id:locationIds){
                    PlaceVo placeVo = iPlaceService.queryById(id);
                    locationNames.add(ObjectUtil.isNull(placeVo) ? null : placeVo.getPlaceName());
                }
                scheduleVo.setLocationNames(locationNames);
            }
//            if(StringUtils.isNotEmpty(professional)){
//                List<Long> professionalIds = Arrays.stream(professional.split(",")).map(Long::parseLong).collect(Collectors.toList());
//                List<String> professionalNames=new ArrayList<>();
//                for(Long id:professionalIds){
//                    String professionalName = deptService.selectDeptNameByDeptId(id);
//                    professionalNames.add(professionalName);
//                }
//                scheduleVo.setProfessionalNames(professionalNames);
//            }
            if(StringUtils.isNotEmpty(college)){
                List<Long> collegeIds = Arrays.stream(college.split(",")).map(Long::parseLong).collect(Collectors.toList());
                List<String> collegeNames=new ArrayList<>();
                for(Long id:collegeIds){
                    String collegeName = deptService.selectDeptNameByDeptId(id);
                    collegeNames.add(collegeName);
                }
                scheduleVo.setCollegeNames(collegeNames);
            }
            if(StringUtils.isNotEmpty(yearGroups)){
                List<Long> yearGroupsIds = Arrays.stream(yearGroups.split(",")).map(Long::parseLong).collect(Collectors.toList());
                List<String> yearGroupsNames=new ArrayList<>();
                for(Long id:yearGroupsIds){
                    TeachClassVo teachClassVo = teachClassService.queryById(id);
                    yearGroupsNames.add(ObjectUtil.isNull(teachClassVo) ? null : teachClassVo.getClassName());
                }
                scheduleVo.setClassNames(yearGroupsNames);
            }

        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询阳光跑计划表列表
     */
    @Override
    public List<ScheduleVo> queryList(ScheduleBo bo) {
        QueryWrapper<Schedule> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private QueryWrapper<Schedule> buildQueryWrapper(ScheduleBo bo) {
        Map<String, Object> params = bo.getParams();
        QueryWrapper<Schedule> lqw = new QueryWrapper<>();
        lqw.like(StringUtils.isNotBlank(bo.getScheduleName()), "prs.schedule_name", bo.getScheduleName());
        lqw.eq(bo.getScheduleId()!=null, "prs.schedule_id", bo.getScheduleId());
        //        lqw.eq(StringUtils.isNotBlank(bo.getLocation()), Schedule::getLocation, bo.getLocation());
//        lqw.eq(StringUtils.isNotBlank(bo.getYears()), Schedule::getYears, bo.getYears());
        lqw.eq(StringUtils.isNotBlank(bo.getSemester()), "prs.semester", bo.getSemester());
//        lqw.eq(StringUtils.isNotBlank(bo.getRuleId()), Schedule::getRuleId, bo.getRuleId());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), "prs.status ", bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getScoreConfigId()), "prs.score_config_id ", bo.getScoreConfigId());
        lqw.eq(StringUtils.isNotBlank(bo.getAcademicYears()), "prs.academic_years ", bo.getAcademicYears());
        return lqw;
    }

    /**
     * 新增阳光跑计划表
     */
    @Override
    public Boolean insertByBo(ScheduleBo bo) {
        Schedule add = MapstructUtils.convert(bo, Schedule.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setScheduleId(add.getScheduleId());
        }
        return flag;
    }

    /**
     * 修改阳光跑计划表
     */
    @Override
    public Boolean updateByBo(ScheduleBo bo) {
        Schedule update = MapstructUtils.convert(bo, Schedule.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Schedule entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除阳光跑计划表
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public String selectScheduleNameById(Long scheduleId) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        Schedule schedule = baseMapper.selectOne(new LambdaQueryWrapper<Schedule>()
            .select(Schedule::getScheduleName).eq(Schedule::getScheduleId, scheduleId).eq(Schedule::getTenantId,loginUser.getTenantId()));
        return ObjectUtil.isNull(schedule) ? null : schedule.getScheduleName();
    }
}
